package config

import (
	"crypto/tls"
	"encoding/base64"
	"flag"
	"log"
	"strconv"
)

type config struct {
	Port     int    `json:"port"`
	Username string `json:"username"`
	Password string `json:"password"`
	CertFile string `json:"certFile"`
	KeyFile  string `json:"keyFile"`
}

var Config = new(config)

func init() {
	flag.IntVar(&Config.Port, "p", 9000, "https监听端口，默认值:9000")
	flag.StringVar(&Config.Username, "u", "", "https认证用户名，默认值:\"\"")
	flag.StringVar(&Config.Password, "P", "", "https认证密码，默认值:\"\"")
	flag.StringVar(&Config.CertFile, "cert", "", "https证书文件，默认值:\"\"")
	flag.StringVar(&Config.KeyFile, "key", "", "https私钥文件，默认值:\"\"")
	flag.Parse()
	if Config.CertFile == "" {
		log.Fatalln("https证书文件不能为空")
	}
	if Config.KeyFile == "" {
		log.Fatalln("https私钥文件不能为空")
	}
	auth := GetAuthorization()
	if auth != "" {
		log.Printf("Proxy-Authorization: %s\n", GetAuthorization())
	}
}

func GetListenAddr() string {
	return "0.0.0.0:" + strconv.Itoa(Config.Port)
}

func GetTlsConfig() *tls.Config {
	cert, err := tls.LoadX509KeyPair(Config.CertFile, Config.KeyFile)
	if err != nil {
		log.Fatalln(err)
	}
	return &tls.Config{Certificates: []tls.Certificate{cert}}
}

func GetAuthorization() string {
	if Config.Username == "" || Config.Password == "" {
		return ""
	}
	auth := Config.Username + ":" + Config.Password
	authHeader := base64.StdEncoding.EncodeToString([]byte(auth))
	return "Basic " + authHeader
}
